﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Core;
using Core.DataProvider;

namespace Service.Forwarder
{
    public partial class ForwarderService : ServiceBase
    {
        public ServiceHost serviceHost = null;
        public static Collection<Entity> entityCollection = new Collection<Entity>();
        public static bool isCommandline = false;
        public static SqlConnector sqlConnector = new SqlConnector();

        public ForwarderService()
        {
            ServiceName = "SqlMonitoring.Forwarder";
        }

        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                foreach (string option in args)
                {
                    switch (option.ToLower(CultureInfo.InvariantCulture))
                    {
                        case "d":
                        case "-d":
                        case "debug":
                        case "-debug":
                            isCommandline = true;
                            break;
                    }
                }
            }

            if (isCommandline)
            {
                ForwarderService forwarderService = new ForwarderService();
                forwarderService.StartService();
                Thread.Sleep(Timeout.Infinite);
            }
            else
            {
                ServiceBase.Run(new ForwarderService());
            }
        }

        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            serviceHost = new ServiceHost(typeof(Monitoring));
            serviceHost.Open();
            Logging.LogInformation("Forwarder service is listening...");
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }

        void StartService()
        {
            OnStart(new string[] { });
        }

        void StopService()
        {
            OnStop();
        }
    }
}
